package com.wframe.project.jnd.dao;

import com.alibaba.fastjson.JSON;
import com.frame.database.JdataBean;
import com.wframe.framework.database.BaseDao;
import com.wframe.project.former.entity.ProductsAttrvalBean;
import com.wframe.project.jnd.entity.UiFloor;
import com.wframe.project.jnd.entity.UiFloorItem;
import com.wframe.project.jnd.entity.UiFloorPanel;
import com.wframe.project.jnd.entity.UiFloorProduct;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * Created by Administrator on 2017/5/24.
 */
@Repository
public class UiFloorDao extends BaseDao {

    public ArrayList<UiFloor> getAvailableFloors(UiFloor.Platform platform) {
        if (platform == null) {
            return null;
        }
        String sql = AVAILABLE_FLOORS_SQL;
        Object[] params = new Object[]{platform.toString()};
        List<JdataBean> result = super.querySql(sql, params);

        String ui_floor_prefix = "f_";
        String ui_floor_panel_prefix = "p_";
        ArrayList<UiFloor> floorList = new ArrayList<UiFloor>();
        if (result != null && result.size() > 0) {
            UiFloor tempFloor = null;
            floorsLoop:
            for (int i = 0, l = result.size(); i < l; i++) {
                JdataBean jdataBean = result.get(i);
                UiFloorPanel floorPanel = buildUiFloorPanel(jdataBean, ui_floor_panel_prefix);
                if (tempFloor == null) {
                    tempFloor = buildUiFloor(jdataBean, ui_floor_prefix);
                }

                if (floorPanel != null && tempFloor != null && tempFloor.getId() != null && floorPanel.getUi_floor_id() != null) {

                    if (floorPanel.getUi_floor_id().longValue() == tempFloor.getId().longValue()) {
                        if (tempFloor.getPanels() == null) {
                            tempFloor.setPanels(new ArrayList<UiFloorPanel>());
                        }
                        floorPanel = setPanelData(floorPanel);
                        tempFloor.getPanels().add(floorPanel);
                        if (i < (l - 1)) {
                            continue floorsLoop;
                        }
                    }

                    UiFloor uiFloor = null;

                    int floorTempIndex = floorList.indexOf(tempFloor);
                    if (floorTempIndex < 0) {
                        uiFloor = tempFloor;
                    } else {
                        uiFloor = floorList.get(floorTempIndex);
                        if (uiFloor.getPanels() == null) {
                            uiFloor.setPanels(new ArrayList<UiFloorPanel>());
                        }
                        uiFloor.getPanels().addAll(tempFloor.getPanels());
                        floorList.remove(floorTempIndex);
                    }
                    floorList.add(uiFloor);
                    tempFloor = null;

                }
            }
        }

        Collections.sort(floorList, new Comparator<UiFloor>() {
            @Override
            public int compare(UiFloor o1, UiFloor o2) {
                if (o1 != null && o1.getSort_value() != null && o2 != null && o2.getSort_value() != null) {
                    return o2.getSort_value() - o1.getSort_value();
                }
                return 0;
            }
        });

        return floorList;
    }

    public UiFloorPanel setPanelData(UiFloorPanel uiFloorPanel) {
        if (uiFloorPanel == null || uiFloorPanel.getId() == null || uiFloorPanel.getType() == null) {
            return null;
        }
        switch (uiFloorPanel.getType()) {
            case ITEM:
                if (uiFloorPanel.getItems() == null || uiFloorPanel.getItems().size() < 1) {
                    List<UiFloorItem> uiFloorItems = getUiFloorItems(uiFloorPanel.getId());
                    uiFloorPanel.setItems(uiFloorItems);
                }
                break;
            case PRODUCT:
                if (uiFloorPanel.getProducts() == null || uiFloorPanel.getProducts().size() < 1) {
                    List<UiFloorProduct> uiFloorProducts = getUiFloorProducts(uiFloorPanel.getId(), null);
                    uiFloorPanel.setProducts(uiFloorProducts);
                }
                break;
        }
        return uiFloorPanel;
    }

    public List<UiFloorItem> getUiFloorItems(Long panelId) {
        if (panelId == null) {
            return null;
        }
        String sql = " SELECT * FROM ui_floor_item WHERE ui_floor_panel_id = ? ";
        Object[] params = new Object[]{panelId};
        List<JdataBean> jdataBeans = super.querySql(sql, params);
        List<UiFloorItem> uiFloorItems = new ArrayList<UiFloorItem>();
        if (jdataBeans != null && jdataBeans.size() > 0) {
            for (int i = 0, l = jdataBeans.size(); i < l; i++) {
                uiFloorItems.add(buildUiFloorItem(jdataBeans.get(i), null));
            }
        }
        return uiFloorItems;
    }

    public List<UiFloorProduct> getUiFloorProducts(Long panelId, Long userId) {
        if (panelId == null) {
            return null;
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ");
        sql.append(" fp.*, p.ID AS p_id, ");
        sql.append(" p.`name` AS p_name, ");
        sql.append(" p.unitname AS p_unitname, ");
        sql.append(" p. CODE AS p_code, ");
        sql.append(" p.attrvals AS p_attrvals, ");
        sql.append(" pp.attrcodes AS p_attrcodes, ");

        if (userId != null) {
            sql.append(" IF ( ");
            sql.append(" ppg.price > 0, ");
            sql.append(" ppg.price, ");
            sql.append(" pp.price ");
            sql.append(" ) AS p_price, ");
        } else {
            sql.append(" pp.price AS p_price , ");
        }

        sql.append(" ( ");
        sql.append(" IFNULL(pp.amount, 0) - IFNULL(pp.djamount, 0) ");
        sql.append(" ) AS p_amount, ");
        sql.append(" pic1.filepath AS p_photourl, ");
        sql.append(" pic1.viewpath AS p_photoview, ");
        sql.append(" pic2.filepath AS p_product_photourl, ");
        sql.append(" pic2.viewpath AS p_product_photoview ");
        sql.append(" FROM ");
        sql.append(" ui_floor_product fp ");
        sql.append(" LEFT JOIN wb_products p ON p.ID = fp.wb_product_id ");
        sql.append(" LEFT JOIN wb_products_prices pp ON p.ID = pp.productid ");
        sql.append(" LEFT JOIN wb_products_pricegrade ppg ON ppg.productid = p.ID ");

        if (userId != null) {
            sql.append(" LEFT JOIN wbuser u ON u.ID = ? AND u.pricegrade = ppg.grade ");
        }

        sql.append(" LEFT JOIN app_pictures pic1 ON pic1.id = pp.photo ");
        sql.append(" LEFT JOIN app_pictures pic2 ON pic2.id = p.photo ");
        sql.append(" WHERE ");
        sql.append(" fp.ui_floor_panel_id = ? ");
        sql.append(" GROUP BY ");
        sql.append(" fp.id ");
        sql.append(" ORDER BY ");
        sql.append(" fp.sort_value DESC ");
        Object[] params = null;

        if (userId != null) {
            params = new Object[]{userId, panelId};
        } else {
            params = new Object[]{panelId};
        }

        List<JdataBean> jdataBeans = super.querySql(sql.toString(), params);

        List<UiFloorProduct> uiFloorProducts = new ArrayList<UiFloorProduct>();
        String productPrefix = "p_";

        Iterator<JdataBean> iterator = jdataBeans.iterator();
        while (iterator.hasNext()) {
            JdataBean product = iterator.next();
            String photo = product.getString(productPrefix + "photoview");
            if (StringUtils.isBlank(photo)) {
                photo = product.getString(productPrefix + "product_photoview");
            }
            product.put(productPrefix + "photo", photo);
            String attrjson = product.getString(productPrefix + "attrvals");
            if (StringUtils.isNotBlank(attrjson)) {
                try {
                    List<ProductsAttrvalBean> jsonarr = JSON.parseArray(attrjson, ProductsAttrvalBean.class);
                    for (ProductsAttrvalBean attrbean : jsonarr) {
                        product.put(productPrefix + attrbean.getAttrcode(), attrbean.getValtxt());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            uiFloorProducts.add(buildUiFloorProduct(product, null, productPrefix));
        }

        return uiFloorProducts;
    }

    private static final String AVAILABLE_FLOORS_SQL = "SELECT " +
            " ff.id AS f_id, " +
            " ff.create_time AS f_create_time, " +
            " ff.title AS f_title, " +
            " ff.color AS f_color, " +
            " ff.platform AS f_platform, " +
            " ff.sort_value AS f_sort_value, " +
            " ff.state AS f_state, " +
            " ff.remark AS f_remark, " +
            " pp.id AS p_id, " +
            " pp.ui_floor_id AS p_ui_floor_id, " +
            " pp.create_time AS p_create_time, " +
            " pp.title AS p_title, " +
            " pp.title_mode AS P_title_mode, " +
            " pp.image AS p_image, " +
            " pp.color AS p_color, " +
            " pp.link AS p_link, " +
            " pp.layout AS p_layout, " +
            " pp.sort_value AS p_sort_value, " +
            " pp.type AS p_type, " +
            " pp.state AS p_state, " +
            " pp.remark AS p_remark " +
            " FROM " +
            " ui_floor ff " +
            " INNER JOIN ui_floor_panel pp ON ff.id = pp.ui_floor_id " +
            " WHERE " +
            " ff.platform = ? " +
            " AND ff.state = 'AVAILABLE' " +
            " AND pp.state = 'AVAILABLE' " +
            " ORDER BY " +
            " ff.sort_value DESC, " +
            " pp.sort_value DESC, " +
            " ff.create_time DESC, " +
            " pp.create_time DESC ";

    private UiFloorPanel buildUiFloorPanel(JdataBean jdataBean, String prefix) {
        String ui_floor_panel_prefix = prefix == null ? "" : prefix;
        UiFloorPanel floorPanel = new UiFloorPanel();
        floorPanel.setId(jdataBean.getLong(ui_floor_panel_prefix + "id"));
        floorPanel.setUi_floor_id(jdataBean.getLong(ui_floor_panel_prefix + "ui_floor_id"));
        floorPanel.setCreate_time((Date) jdataBean.get(ui_floor_panel_prefix + "create_time"));
        floorPanel.setTitle(jdataBean.getString(ui_floor_panel_prefix + "title"));
        floorPanel.setTitle_mode(jdataBean.getString(ui_floor_panel_prefix + "title_mode") == null ? null : UiFloorPanel.TitleMode.valueOf(jdataBean.getString(ui_floor_panel_prefix + "title_mode")));
        floorPanel.setImage(jdataBean.getString(ui_floor_panel_prefix + "image"));
        floorPanel.setColor(jdataBean.getString(ui_floor_panel_prefix + "color"));
        floorPanel.setLink(jdataBean.getString(ui_floor_panel_prefix + "link"));
        floorPanel.setLayout(jdataBean.getString(ui_floor_panel_prefix + "layout") == null ? null : UiFloorPanel.Layout.valueOf(jdataBean.getString(ui_floor_panel_prefix + "layout")));
        floorPanel.setSort_value(jdataBean.getInteger(ui_floor_panel_prefix + "sort_value"));
        floorPanel.setType(jdataBean.getString(ui_floor_panel_prefix + "type") == null ? null : UiFloorPanel.Type.valueOf(jdataBean.getString(ui_floor_panel_prefix + "type")));
        floorPanel.setState(jdataBean.getString(ui_floor_panel_prefix + "state") == null ? null : UiFloorPanel.State.valueOf(jdataBean.getString(ui_floor_panel_prefix + "state")));
        floorPanel.setRemark(jdataBean.getString(ui_floor_panel_prefix + "remark"));
        return floorPanel;
    }

    private UiFloor buildUiFloor(JdataBean jdataBean, String prefix) {
        String ui_floor_prefix = prefix == null ? "" : prefix;
        UiFloor tempFloor = new UiFloor();
        tempFloor.setId(jdataBean.getLong(ui_floor_prefix + "id"));
        tempFloor.setCreate_time((Date) jdataBean.get(ui_floor_prefix + "create_time"));
        tempFloor.setTitle(jdataBean.getString(ui_floor_prefix + "title"));
        tempFloor.setColor(jdataBean.getString(ui_floor_prefix + "color"));
        tempFloor.setPlatform(jdataBean.getString(ui_floor_prefix + "platform") == null ? null : UiFloor.Platform.valueOf(jdataBean.getString(ui_floor_prefix + "platform")));
        tempFloor.setSort_value(jdataBean.getInteger(ui_floor_prefix + "sort_value"));
        tempFloor.setState(jdataBean.getString(ui_floor_prefix + "state") == null ? null : UiFloor.State.valueOf(jdataBean.getString(ui_floor_prefix + "state")));
        tempFloor.setRemark(jdataBean.getString(ui_floor_prefix + "remark"));
        return tempFloor;
    }

    private UiFloorItem buildUiFloorItem(JdataBean jdataBean, String prefix) {
        String ui_floor_item_prefix = prefix == null ? "" : prefix;
        UiFloorItem UiFloorItem = new UiFloorItem();
        UiFloorItem.setId(jdataBean.getLong(ui_floor_item_prefix + "id"));
        UiFloorItem.setUi_floor_panel_id(jdataBean.getLong(ui_floor_item_prefix + "ui_floor_panel_id"));
        UiFloorItem.setCreate_time((Date) jdataBean.get(ui_floor_item_prefix + "create_time"));
        UiFloorItem.setTitle(jdataBean.getString(ui_floor_item_prefix + "title"));
        UiFloorItem.setImage(jdataBean.getString(ui_floor_item_prefix + "image"));
        UiFloorItem.setLink(jdataBean.getString(ui_floor_item_prefix + "link"));
        UiFloorItem.setCss(jdataBean.getString(ui_floor_item_prefix + "css"));
        UiFloorItem.setSort_value(jdataBean.getInteger(ui_floor_item_prefix + "sort_value"));
        UiFloorItem.setRemark(jdataBean.getString(ui_floor_item_prefix + "remark"));
        return UiFloorItem;
    }

    private UiFloorProduct buildUiFloorProduct(JdataBean jdataBean, String prefix, String productPrefix) {
        String ui_floor_product_prefix = prefix == null ? "" : prefix;
        UiFloorProduct uiFloorProduct = new UiFloorProduct();
        uiFloorProduct.setId(jdataBean.getLong(ui_floor_product_prefix + "id"));
        uiFloorProduct.setUi_floor_panel_id(jdataBean.getLong(ui_floor_product_prefix + "ui_floor_panel_id"));
        uiFloorProduct.setWb_product_id(jdataBean.getLong(ui_floor_product_prefix + "wb_product_id"));
        uiFloorProduct.setSort_value(jdataBean.getInteger(ui_floor_product_prefix + "sort_value"));
        uiFloorProduct.setRemark(jdataBean.getString(ui_floor_product_prefix + "remark"));
        Map<String, Object> productInfo = new HashMap<String, Object>();
        Map<String, Object> dataMap = jdataBean.getDataMap();
        if (dataMap != null && productPrefix != null) {
            Set<Map.Entry<String, Object>> entrySet = dataMap.entrySet();
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                if (next != null && next.getKey() != null && next.getKey().startsWith(productPrefix)) {
                    productInfo.put((next.getKey() + " ").substring(productPrefix.length()).trim(), next.getValue());
                }
            }
        }
        uiFloorProduct.setProduct_info(productInfo);
        return uiFloorProduct;
    }

    public UiFloorItem findOne(String id) {
        String sql = "select * from ui_floor_item where id=?";
        JdataBean bean = uniqueResult(sql, id);
        return buildUiFloorItem(bean, null);
    }

}
